package com.lovo.util;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lovo.bean.UsersBean;
import com.lovo.result.GlobalHandleException;
import com.lovo.result.Result;
import com.lovo.service.IUsersService;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;

import javax.servlet.ServletResponse;
import java.io.IOException;

public class WebUtil {
    public static void writeValueAsString(ServletResponse response, Result result) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(mapper.writeValueAsString(result));
    }

    /**
     * 验证token的有效性
     * @param token
     * @return token对应的用户对象，如果为null表示验证失败
     * @throws IOException
     */
    public static UsersBean verifyToken(String token, IUsersService userService) {
        if(token == null){
            return null;
        }
        String userName = null;
        try {
            userName = JWTUtil.getAudience(token);
        } catch (GlobalHandleException e) {
            return null;
        }
        UsersBean userInfoBean =(UsersBean) userService.selectByUserName(userName);
        if(userInfoBean == null){
            return null;
        }
        try {
            JWTUtil.verifyToken(token,userInfoBean.getUserPwd());
        } catch (GlobalHandleException e) {
            e.printStackTrace();
        }

        return userInfoBean;
    }
    /**
     * 封装请求信息对象
     * @return
     */
    public static HttpEntity httpEntity() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
        headers.add("accept","application/json");
        HttpEntity<HttpHeaders> request = new HttpEntity<>(headers);
        return request;
    }

}
